package appnode;

import javax.jdo.PersistenceManager;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import java.util.List;
import java.util.ArrayList;
import appnode.Node;
import appnode.SearchNode;
import appnode.Link;
import appnode.Ratings;
import javax.jdo.Query;
import java.lang.*;

import appnode.Tablemsgs;
import appnode.Messages;
import appnode.SearchNode;
import appnode.PMF;

public class Msgtools {
	
	public static String Status(Tablemsgs t, String nodename) {
		
		String status = "";
		String check = t.getMessages().get(t.getMessages().size()-1).getFromnode();
		if (nodename.equals(check)) {
			status = "wait for answer"; 
		}
		else {
			status = "you must answer";
		}
	return status;	
	}
	
	public static String sentMsgowner(String fromowner, String toowner) {
		List<Node> fromnodes = SearchNode.getByOwner(fromowner);
		List<Node> tonodes = SearchNode.getByOwner(toowner);
		String sentmsgowner = "no";
		int a = 0;
		for (int i=0;i<fromnodes.size();i++) {
			for (int j=0;j<tonodes.size();j++) {
				if (sentMsg(fromnodes.get(i).getNodename(),tonodes.get(j).getNodename()).equals("yes")) {
					a++;
				} //if
			} //for
		} //for
		if (a!=0) {
			sentmsgowner="yes";
		}
		return sentmsgowner;
	}
	
	
	public static String sentMsg(String fromnode, String tonode) {
		
		String sentmsg = "no";
		int j=0;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		Query query = pm.newQuery(Tablemsgs.class);
		List<Tablemsgs> results = (List<Tablemsgs>) query.execute();
		for (Tablemsgs t : results) {
			boolean a = (fromnode.equals(t.getFromnode())) || (fromnode.equals(t.getTonode()));
			boolean b = (tonode.equals(t.getFromnode())) || (tonode.equals(t.getTonode()));
			if (a && b) {
				for (int i=0;i<t.getMessages().size();i++) {
					if (t.getMessages().get(i).getFromnode().equals(fromnode)) {
						j++;
					} //if	
				} //for
			} //if
		} //for
		if (j!=0) {
			sentmsg = "yes";
		}
	return sentmsg;
	}
}